//
//  OrderViewController.swift
//  BaseSwift
//
//  Created by ghwang on 2019/7/22.
//  Copyright © 2019 ghwang. All rights reserved.
//

import UIKit
import EasyNavigation

class OrderViewController: UIViewController {

    var lastMenuBtn:UIButton? = nil
    var page = 1
    var index:Int = 0
    var dataArray:Array<OrderVo> = Array()
    var orderStatus:String = ""
    
    func sendRequest(){
        
        API.orderList(params: ["page":page.description,
                               "orderStatus":self.orderStatus]) { (result) in
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            
            let pageVo = result as! Page<OrderVo>
            
            if self.page == 1{
                
                self.dataArray = pageVo.list

            }else{
                
                for item in pageVo.list {
                    
                    self.dataArray.append(item)
                }
            }
            
            if pageVo.list.count < 20{
                
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
            
            self.tableView.reloadData()
            
        }
    }
    
    lazy var menuView:UIView = {
        
        let bg = UIView()
        
        //菜单
        let containerView = UIView()
        bg.addSubview(containerView)
        containerView.backgroundColor = UIColor.white
        var temp = Array<UIView>()
        let tits = ["全部订单","待付款","待出行","待评价"]
        
        for sindex in 0 ..< tits.count {
            
            let item = tits.get(at: sindex)
            let menuBtn = UIButton()
            menuBtn.tag = 10086+sindex
            menuBtn.setTitle(item, for: .normal)
            menuBtn.titleLabel?.font = UIFont.commonFont
            menuBtn.setTitleColor(UIColor.textTitleColorBlack, for: .normal)
            menuBtn.addTarget(self, action: #selector(menuClick), for: .touchUpInside)
            containerView.addSubview(menuBtn)
            let _ = menuBtn.sd_layout()?.heightIs(44)
            let bline = UIView()
            bline.backgroundColor = UIColor.GP_Orange_Color
            bline.tag = 1900
            menuBtn.addSubview(bline)
            
            
            if sindex == 0 {
                
                let _ = bline.sd_layout()?.widthIs(66)!.heightIs(4)!.bottomSpaceToView(menuBtn,6)?.centerXEqualToView(menuBtn)

                
            }else{
                
                let _ = bline.sd_layout()?.widthIs(50)!.heightIs(4)!.bottomSpaceToView(menuBtn,6)?.centerXEqualToView(menuBtn)

            }
            
            
            temp.append(menuBtn)
            if sindex == self.index {
                
                bline.isHidden = false
                self.lastMenuBtn = menuBtn
                
            }else{
                bline.isHidden = true

            }
            
            
        }
        let _ = containerView.sd_layout()?.topSpaceToView(bg,0)?.widthRatioToView(bg,1)
        
        containerView.setupAutoWidthFlowItems(temp, withPerRowItemsCount: 4, verticalMargin: 0, horizontalMargin: 0, verticalEdgeInset: 0, horizontalEdgeInset: 0)
        
        return bg
        
        
    }()
    lazy var tableView:UITableView = {
        
        
        var tableView = UITableView()
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = UIColor.clear
        tableView.tableFooterView = UIView()
        tableView.separatorColor = UIColor.clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(UINib.init(nibName: "OrderCell", bundle: nil), forCellReuseIdentifier: "OrderCell")
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.backgroundColor
        self.navigationView.setTitle("订单")
        if self.index == 0 {
            
            self.orderStatus = ""
        }else if self.index == 1{
            
            self.orderStatus =  "NEW"
            
        }else if self.index == 2{
            
            self.orderStatus =  "SUCCESS"

        }else{
            
            self.orderStatus = "FINISH"
        }
        initViews()
        
        
    }
    func initViews() {
          
        view.addSubview(menuView)
        let _ = menuView.sd_layout()?.widthRatioToView(view,1)!.heightIs(44)!.topSpaceToView(self.view,HT_StatusBarAndNavigationBarHeight)
        self.view.addSubview(tableView)
        let _ = tableView.sd_layout()?.spaceToSuperView(UIEdgeInsets(top: HT_StatusBarAndNavigationBarHeight+44, left: 0, bottom: HT_TabbarSafeBottomMargin, right: 0))
        
        
        let header = MJRefreshNormalHeader.init {
            
            self.page = 1
            self.sendRequest()
        }
        header?.stateLabel.isHidden = true
        header?.lastUpdatedTimeLabel.isHidden = true
        self.tableView.mj_header = header
        
        let footer = MJRefreshAutoNormalFooter.init {

            self.page += 1
            self.sendRequest()
        }
        self.tableView.mj_footer = footer
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        page = 1
        sendRequest()

    }
    @objc func menuClick(btn:UIButton){
        
        let bline = btn.viewWithTag(1900)
        bline?.isHidden = false
        
        if lastMenuBtn != btn {
            
            let bline1 = lastMenuBtn!.viewWithTag(1900)
            bline1?.isHidden = true
            
        }
        
        self.lastMenuBtn = btn
        self.page = 1
        if btn.tag == 10086 {
            
            self.orderStatus = ""
        }else if btn.tag == 10087{
            
            self.orderStatus =  "NEW"
            
        }else if btn.tag == 10088{
            self.orderStatus =  "SUCCESS"

        }else{
            self.orderStatus = "FINISH"
        }
        sendRequest()
        
    }
}

extension OrderViewController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 195
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let mod = self.dataArray.get(at: indexPath.row)

        let cell = tableView.dequeueReusableCell(withIdentifier: "OrderCell") as! OrderCell
        cell.setModel(mod: mod!)
        cell.rightClick = { (order,btn) in
            
            
            if btn.titleLabel?.text == "立即支付" {
                
                let payVC = PayViewController()
                payVC.order = order
                PUSH(from: self, to: payVC)
                
            }else if btn.titleLabel?.text == "退款"{
                
                API.orderCancel(params: ["orderNo":order.orderNo!,
                                         ]) { (result) in
                    
                    
                                            ToastUtil.showHUDSuccess(msg: "申请退款成功")
                }
                
            }else if btn.titleLabel?.text == "评论"{
                

                self.tableView(self.tableView, didSelectRowAt: indexPath)
            }
            
        }
        cell.cancelClick = {order in
            
            API.orderCancel(params: ["orderNo":order.orderNo!,
                                     ]) { (result) in
                
                
                                        ToastUtil.showHUDSuccess(msg: "订单取消成功")
            }
            
        }
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let mod = self.dataArray.get(at: indexPath.row)
        
        API.orderDetail(params: ["orderNo":mod!.orderNo!]) { (result) in
            
            let dvc = OrderDetailVC()
            dvc.order = (result as! OrderVo)
            PUSH(from: self, to: dvc)
            
        }
        

    }
    
}
